package guice.boot.archive.common.thread;

import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicInteger;


public class NamedThreadFactory implements ThreadFactory {

    /**
     * The global thread pool counter
     */
    private static final AtomicInteger POOL_COUNT = new AtomicInteger();
    /**
     * The first default prefix of thread name
     */
    private final static String FIRST_PREFIX = "SOFA-ARK-";
    /**
     * The current thread pool counter
     */
    private final AtomicInteger threadCount = new AtomicInteger(1);
    /**
     * Thread threadGroup
     */
    private final ThreadGroup threadGroup;
    /**
     * Thread name prefix
     */
    private final String namePrefix;
    /**
     * Thread daemon option
     */
    private final boolean isDaemon;

    /**
     * specify the second prefix of thread name, default the thread created is non-daemon
     *
     * @param secondPrefix second prefix of thread name
     */
    public NamedThreadFactory(String secondPrefix) {
        this(secondPrefix, false);
    }

    /**
     * Construct a named thread factory
     *
     * @param secondPrefix second prefix of thread name
     * @param daemon       thread daemon option
     */
    public NamedThreadFactory(String secondPrefix, boolean daemon) {
        SecurityManager securityManager = System.getSecurityManager();
        threadGroup = (securityManager != null) ? securityManager.getThreadGroup() : Thread.currentThread().getThreadGroup();
        namePrefix = FIRST_PREFIX + secondPrefix + "-" + POOL_COUNT.getAndIncrement() + "-T";
        isDaemon = daemon;
    }

    @Override
    public Thread newThread(Runnable runnable) {
        Thread thread = new Thread(threadGroup, runnable, namePrefix + threadCount.getAndIncrement(), 0);
        thread.setDaemon(isDaemon);
        if (thread.getPriority() != Thread.NORM_PRIORITY) {
            thread.setPriority(Thread.NORM_PRIORITY);
        }
        return thread;
    }
}